package com.deductive.netty.websocket.config;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

@Component
public class NettyWebSocketServer {

    private static final Logger logger = LoggerFactory.getLogger(NettyWebSocketServer.class);

    private EventLoopGroup bossGroup;
    private EventLoopGroup workerGroup;

    @PostConstruct
    public void start() throws Exception {
        // 配置事件循环组的线程数
        int bossThreads = Math.max(1, Runtime.getRuntime().availableProcessors() / 2);
        int workerThreads = Runtime.getRuntime().availableProcessors() * 2;

        bossGroup = new NioEventLoopGroup(bossThreads);
        workerGroup = new NioEventLoopGroup(workerThreads);

        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new NettyWebSocketServerInitializer())

                // --- 性能优化配置 ---

                // 设置传入连接指示的最大队列长度
                .option(ChannelOption.SO_BACKLOG, 1024)

                // 使用池化字节缓冲区分配器以减少内存分配和GC压力
                .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)

                // 启用TCP保活以维持长连接
                .childOption(ChannelOption.SO_KEEPALIVE, true)

                // 禁用Nagle算法以减少小而频繁消息的延迟
                .childOption(ChannelOption.TCP_NODELAY, true)

                // 设置TCP发送和接收缓冲区大小（可选，操作系统通常会自动调优）
                .childOption(ChannelOption.SO_SNDBUF, 65536)
                .childOption(ChannelOption.SO_RCVBUF, 65536);

        ChannelFuture future = bootstrap.bind(8081).sync();
        if (future.isSuccess()) {
            logger.info("Netty WebSocket服务器已在端口8081启动，使用{}个boss线程和{}个worker线程", bossThreads, workerThreads);
        } else {
            logger.error("启动Netty WebSocket服务器失败", future.cause());
        }
    }

    @PreDestroy
    public void stop() {
        logger.info("正在关闭Netty WebSocket服务器...");
        if (bossGroup != null) {
            bossGroup.shutdownGracefully();
        }
        if (workerGroup != null) {
            workerGroup.shutdownGracefully();
        }
        logger.info("Netty WebSocket服务器已关闭");
    }
}